<template>
  <a-row>
    <a-col class="leftCol" :span="8">
      <a-card class="cardSelect" :bordered="true">
        <div class="selectAppId">
          选择应用:
          <a-select
            showSearch
            placeholder="选择应用"
            optionFilterProp="children"
            style="width: 200px"
            :filterOption="filterOption"
            v-model="huiwAppId"
            @change="appIdChange"
          >
            <a-select-option v-for="item in huiwAppIds" :value="item.appId" :key="item.appId">
              {{ item.appInfo }}
            </a-select-option>
          </a-select>
          <a-button style="margin-left: 5px" type="primary" shape="round" size="small" @click="getTopMenu" >查询</a-button>
        </div>
      </a-card>
      <a-card class="card" :loading="cardloading" :bordered="true">
        <a-row>
          <a-col :span="24">
            <div class="table-operations">
              <a-button
                ghost
                value="small"
                v-if="addBtnShow"
                type="primary"
                icon="plus"
                @click="handleMenuAdd()">
                新增菜单
              </a-button>
              <a-button
                value="small"
                v-if="delBtnShow"
                type="danger"
                icon="close"
                @click="handleMenuDel()">
                删除选中
              </a-button>
            </div>
            <!-- <a-divider orientation="left"></a-divider> -->
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" style="border: 1px;">
            <div class="tree-operations">
              <a-directory-tree
                :loadData="onLoadData"
                :treeData="treeData"
                :selectedKeys="selectedKeys"
                @select="onSelect"
                @expand="onExpand">
              </a-directory-tree>
            </div>
          </a-col>
        </a-row>
      </a-card>
    </a-col>
    <a-col :span="16">
      <a-card class="card" :bordered="true">
        <a-row :gutter="24">
          <a-col :span="24">
            <a-alert
              v-if="alertVisable"
              showIcon
              banner
              message="保存失败,请检查内容是否填写正确"
              type="error"
              closable
              @close="alertOnClose"
            />
          </a-col>
        </a-row>
        <div>
          <a-form :form="form">
            <!-- 菜单名称 category -->
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item
                  label="菜单名称"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-input :disabled="menuInfoCardloading" v-decorator="['menuName', {rules: [{ required: true, message: '请填写菜单名称' }]}]" />
                </a-form-item>
              </a-col>
            </a-row>
            <!-- 菜单代码 -->
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item
                  label="菜单代码"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-input :disabled="menuInfoCardloading" v-decorator="['menuCode', {rules: [{ required: true, message: '请填写菜单代码' }]}]" />
                </a-form-item>
              </a-col>
            </a-row>
            <!-- 菜单名称 category -->
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item
                  label="菜单Url"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-input :disabled="menuInfoCardloading" v-decorator="['menuUrl', {rules: [{ required: true, message: '请填写菜单Url' }]}]" />
                </a-form-item>
              </a-col>
            </a-row>
            <!-- 菜单名称 category -->
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item
                  label="菜单图标"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-input :disabled="menuInfoCardloading" v-decorator="['menuIcon']" />
                </a-form-item>
              </a-col>
            </a-row>
            <!-- 菜单名称 category -->
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item
                  label="打开方式"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-select :disabled="menuInfoCardloading" defaultValue="1" style="width: 100%" v-decorator="['openType', {rules: [{ required: true, message: '请设定打开方式' }]}]">
                    <a-select-option v-for="item in openTypes" :value="item.key" :key="item.key">
                      {{ item.lable }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <!-- 显示控制 -->
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item
                  label="显示控制"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-select :disabled="menuInfoCardloading" defaultValue="1" style="width: 100%" v-decorator="['onshow', {rules: [{ required: true, message: '请设定显示控制' }]}]">
                    <a-select-option value="1" key="1">
                      显示
                    </a-select-option>
                    <a-select-option value="0" key="0">
                      隐藏
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item
                  label="其他信息"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-textarea :disabled="menuInfoCardloading" :rows="4" v-decorator="['memo', {}]" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <div class="menuInfodiv">
                  <a-button :disabled="menuInfoCardloading" value="small" type="primary" @click="handleMenuSave()">保存</a-button>
                  <a-button :disabled="menuInfoCardloading" value="small" @click="handleMenuRest()">重置</a-button>
                </div>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- <menu-modal ref="MenuModal" @close="handleMenuModalClose" /> -->
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
// import MenuModal from './modules/MenuModal'
import { getMenuByParentMenu, getMenuInfo, saveMenuInfo, delMenu } from './menu'
import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'

export default {
  name: 'MenuManager',
  components: {
    // MenuModal
  },
  data () {
    return {
      // 中文
      locale: zhCN,
      openTypes: [
        { key: '1', lable: '内部' },
        { key: '2', lable: '外部' }
      ],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      alertVisable: false,
      huiwAppId: '',
      huiwAppIds: [
        { appId: 'huiwcore', appInfo: '平台应用' }
      ],
      cardloading: false,
      menuInfoCardloading: true,
      delBtnShow: false, // 删除按钮显示控制
      addBtnShow: false, // 添加按钮显示控制
      treeData: [], // 菜单树
      selectedNodes: [],
      selectedKeys: [''], // 选中的菜单
      menuInfo: {
        sysSeq: 0,
        pid: ''
      }
    }
  },
  created () {
    this.form = this.$form.createForm(this)
  },
  mounted () {
  },
  methods: {
    // 菜单树点击按钮
    onSelect (selectedKeys, info) {
      this.menuInfoCardloading = true
      // 加载子节点
      const treeNode = info.node
      // 选中显示删除按钮
      if (selectedKeys.length > 0) {
        this.delBtnShow = true
      }
      getMenuByParentMenu(treeNode.dataRef.key, this.huiwAppId, {})
        .then(res => {
          if (res) {
            if (res.code !== 'C0') {
              treeNode.dataRef.children = []
              var menus = res.data
              for (var i = 0; i < menus.length; i++) {
                var tn = {
                  title: menus[i].menuName,
                  key: menus[i].pid
                }
                treeNode.dataRef.children.push(tn)
              }
              this.treeData = [...this.treeData]
            }
          }
        })
      // 结束
      this.selectedKeys = [selectedKeys[0]] // 节点单选
      this.selectedNodes = [info] // 节点单选
      if (this.selectedKeys) {
        this.getMenuInfo(this.selectedKeys[0])
      }
      this.menuInfoCardloading = false
    },
    // 选择应用
    appIdChange (value) {
      console.log(value)
      if (value) {
        this.selectedKeys = [value]
        this.getTopMenu()
        this.addBtnShow = true
      }
    },
    // 初始顶级菜单
    getTopMenu () {
      this.treeData = []
      new Promise((resolve) => {
        resolve(getMenuByParentMenu(this.huiwAppId, this.huiwAppId, {}))
      }).then(res => {
        new Promise((resolve) => {
          // resolve(function () {
          console.log(res)
          if (res.code !== 'C0') {
            var menus = res.data
            for (var i = 0; i < menus.length; i++) {
              if (i === 0) {
                // this.selectedKeys = [menus[i].pid]
              }
              var tn = {
                title: menus[i].menuName,
                key: menus[i].pid
              }
              this.treeData.push(tn)
            }
            // if (this.treeData) {
            //   this.treeData.selectedKeys = { [0] }
            // }
            this.cardloading = false
          }
          resolve()
          // })
        }).then(() => {
          if (this.selectedKeys) {
          }
        })
      }).catch(() => {
        // Do something
      }).finally(() => {
      })
    },
    // 树展开按钮
    onExpand () {
      // console.log('Trigger Expand')
    },
    // 树加载节点
    onLoadData (treeNode) {
      console.log('treeNode', treeNode)
      console.log('treeData', this.treeData)
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        getMenuByParentMenu(treeNode.dataRef.key, this.huiwAppId, {})
          .then(res => {
            if (res) {
              if (res.code !== 'C0') {
                treeNode.dataRef.children = []
                var menus = res.data
                for (var i = 0; i < menus.length; i++) {
                  var tn = {
                    title: menus[i].menuName,
                    key: menus[i].pid
                  }
                  treeNode.dataRef.children.push(tn)
                }
                this.treeData = [...this.treeData]
              }
            }
          })
        resolve()
      })
    },
    // 得到菜单详细信息
    getMenuInfo (menuPid) {
      getMenuInfo(menuPid, {})
        .then(res => {
          if (res.code === 'C1' && res.data) {
            this.menuInfo = {
              sysSeq: res.data.sysSeq,
              pid: res.data.pid
            }
            this.form.setFieldsValue(res.data)
          }
        })
    },
    // 增加按钮
    handleMenuAdd () {
      if (this.huiwAppId) {
        this.form.setFieldsValue({
          menuName: '',
          menuUrl: '',
          menuIcon: '',
          openType: '1',
          menuCode: '',
          onshow: '1',
          memo: ''
        })
        this.menuInfo = {
          appId: this.huiwAppId,
          sysSeq: 0,
          pid: '',
          parentMenuPid: this.selectedKeys[0]
        }
        this.menuInfoCardloading = false
      } else {
      }
    },
    // 删除按钮
    handleMenuDel () {
      const _this = this
      const deptPid = _this.selectedKeys[0]
      if (deptPid) {
        _this.$confirm({
          title: '确定移除?',
          content: '该操作将删除菜单,且不可恢复,是否继续删除',
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          // onCancel () {
          // }
          onOk () {
            if (_this.menuInfo) {
              delMenu(_this.menuInfo, {}).then(res => {
                if (res.code === 'C1') {
                  _this.$message.success('该菜单已删除除', 3)
                  _this.selectedKeys = [_this.huiwAppId]
                  _this.getTopMenu()
                  _this.form.setFieldsValue({
                    menuName: '',
                    menuUrl: '',
                    menuIcon: '',
                    openType: '1',
                    memo: ''
                  })
                  _this.menuInfo = {
                    appId: _this.huiwAppId,
                    sysSeq: 0,
                    pid: '',
                    parentMenuPid: _this.selectedKeys[0]
                  }
                  _this.menuInfoCardloading = true
                }
              })
            }
          }
        })
      }
    },
    // 保存按钮
    handleMenuSave () {
      const _this = this
      // 触发表单验证
      _this.form.validateFields((err, values) => {
        // 验证表单没错误
        if (!err) {
          new Promise((resolve) => {
            resolve(saveMenuInfo(Object.assign(_this.menuInfo, _this.form.getFieldsValue()), {}))
          }).then(res => {
            if (res.code === 'C1') {
              _this.$message.success('保存成功', 3)
              _this.alertVisable = false
            } else {
              _this.alertVisable = true
              _this.confirmLoading = false
            }
          }).catch(() => {
            // Do something
          }).finally(() => {
            _this.confirmLoading = false
          })
        }
      })
    },
    // 重置按钮
    handleMenuRest () {
      this.getMenuInfo(this.selectedKeys[0])
    },
    // 编辑保存按钮关闭回调
    handleMenuModalClose () {
      this.onSelect(this.selectedKeys, this.selectedNodes[0])
    },
    // 关闭提示
    alertOnClose () {
      this.alertVisable = false
    },
    // 应用搜索
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    }
  }
}
</script>

<style lang="less">
  .card {
    margin: 10px;
    margin-top: 0px;
    min-height:300px;
    min-width: 300px;
  }
  .table-operations {
    margin-bottom: 10px;
    text-align: right;
    height: 30px;
  }
  .table-operations > button {
    margin-right: 10px;
    margin-top: 0px;
    margin-bottom: 0px;
    // text-align: right;
  }
  .table-operations > input {
    margin-left: 10px;
    // text-align: right;
  }
  .tree-operations {
    margin-bottom: 16px;
    overflow: auto;
    max-height: 500px;
    max-height: calc(100vh - 403px);
    // max-height:-moz-calc(100% - 300px);
    // max-height:-webkit-calc(100% - 300px);
    // float: right;
  }
  .leftCol {
    min-width:300px;
  }
  .cardSelect{
    margin: 10px;
    margin-top: 0px;
    padding: 0px;
    margin-bottom: 10px;
    text-align: left;
    min-width: 300px;
  }
  .cardSelect-select{
    margin-left: 5px;
    widows: 100%;
  }
  .menuInfodiv{
    margin: 10px;
    text-align: center;
  }
  .menuInfodiv > button{
    margin-left: 30px;
  }
</style>
